package study.datastructure.queue.impl;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-10-22 14:38
 */

import study.datastructure.queue.Queue;

import java.util.Iterator;

/**
 * 2024/10/22,
 */


public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {


    private static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    private Node<E> head = new Node<>(null, null);
    private Node<E> tail = head;
    private int size = 0; //节点数
    private int capacity = Integer.MAX_VALUE;//节点容量

    /**
     * 构造链表
     */
    {
        tail.next = head;
    }
    public LinkedListQueue() {

    }
    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) return false;

        Node<E> added = new Node<>(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) return null;
        Node<E> first = head.next;
        head.next = first.next;
        if (first == head) tail = head;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) return null;
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<>(3);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        System.out.println(queue.offer(4));
        queue.offer(5);
        for (Integer integer : queue)
            System.out.println(integer);
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}
